# 所有用户信息
user_list = []


def read_userinfo():
    # 读取用户信息文件对象
    with open("userinfo.txt", encoding="utf-8", mode='r') as f:
        # 读取多行
        content = f.readlines()
        # 读取每一行
        for i in range(len(content)):
            info = content[i].split("|")
            user_dict = {"username": info[0], "password": info[1], "status": info[2]}
            user_list.append(user_dict)


def username_is_exist(username):
    for user in user_list:
        if username == user['username']:
            return True


def verify_password(username, password):
    for user in user_list:
        if username == user['username'] and password == user['password']:
            return user
    return None


def signup():
    # 输入用户名
    username = input("欢迎注册，请输入用户名：")
    # 检查用户名是否存在
    if username_is_exist(username):
        print("用户名已存在，你可以直接登录")
        return
    # 注册
    while True:
        password = input("请输入密码：")
        enpassword = input("请再次输入：")
        if password != enpassword:
            print("两次密码不一致，请重新输入")
        else:
            break
    # 写入用户信息到文件
    with open("userinfo.txt", encoding="utf-8", mode='a') as f:
        f.write(f"{username}|{password}|unlock")
    print(f"注册成功，请牢记您的用户名：'{username}'，密码：'{password}'")


def login():
    # 剩余尝试失败次数
    number_of_attempt = 3
    username = input("欢迎登录，请输入用户名：")
    while True:
        password = input("请输入密码：")
        if not username_is_exist(username):
            username = input("用户名不存在，请重新输入用户名：")
            continue
        while number_of_attempt > 0:
            user_info = verify_password(username, password)
            if user_info is not None:
                print(user_info)
                if user_info['status'].startswith("unlock"):
                    print("登录成功，欢迎进入课堂")
                    return
                else:
                    print("账号处于锁定状态，请找老师解锁")
                    return
            else:
                number_of_attempt -= 1
                password = input(f"密码错误，您还有{number_of_attempt}次机会，请重新输入：")
                continue
        print("密码错误超过3次，账户已被锁定，请联系老师解锁")
        return


if __name__ == '__main__':
    # 读取用户信息
    read_userinfo()
    print(user_list)
    print("欢迎来到Python课堂，请选择您要的功能：\n0 注册\n1 登录\n请输入：", end="")
    while True:
        user_input = input()
        if user_input == '0':
            signup()
            break
        elif user_input == '1':
            login()
            break
        else:
            print("输入错误，请重新输入：", end="")
